<?php
/**
 * Created by PhpStorm.
 * User: Sunqj
 * Date: 2016/12/11
 * Time: 下午8:42
 */
namespace app\api\model;

class EaseMob extends Common
{
    public function register($userName, $password, $nickname = "")
    {
        //获取access_token
        $accessToken = $this->getAccessToken();

        $data = array(
            "username" => $userName,
            "password" => $password,
            "nickname" => $nickname,
        );

        $result = $this->requestApi("users", $data, $accessToken);
    }
    //获取access_token
    private function getAccessToken()
    {
        if (session("H_EASEMOB_ACCESS_TOKEN_TIME") >= time())
        {
            return session("H_EASEMOB_ACCESS_TOKEN");
        }
        else
        {
            $data = array(
                "grant_type" => "client_credentials",
                "client_id" => $this->clientId,
                "client_secret" => $this->clientSecret,
            );

            $result = $this->requestApi("token", $data);

            //保存access_token
            session("H_EASEMOB_ACCESS_TOKEN_TIME", time() + $result["expires_in"]);
            session("H_EASEMOB_ACCESS_TOKEN", $result["access_token"]);

            return $result["access_token"];
        }
    }

    //请求远程API
    private function requestApi($interface, $data, $token = '')
    {
        if (function_exists("curl_init"))
        {
            $client = curl_init();

            //超时时间
            curl_setopt($client, CURLOPT_TIMEOUT, 30);
            curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);

            //请求URL
            $url = $this->apiUrl . "/" . $this->orgName . "/" . $this->appName . "/" . $interface;
            curl_setopt($client, CURLOPT_URL, $url);

            //header信息
            $headers = array();
            $headers[] = "Content-Type: application/json";
            if ($token)
            {
                $headers[] = "Authorization:Bearer " . $token;
            }

            curl_setopt($client, CURLOPT_HTTPHEADER, $headers);


            //启用post方式
            curl_setopt($client, CURLOPT_POST, 1);
            //传输post数据
            curl_setopt($client, CURLOPT_POSTFIELDS, json_encode($data));

            $data = curl_exec($client);
            if($data)
            {
                curl_close($client);
                return json_decode($data, true);
            }
            else
            {
                $error = curl_errno($client);
                curl_close($client);

                send_server_error("即时通讯服务器异常！错误代码(curl)：" . $error);
            }
        }
        
    }

    private $apiUrl = "https://a1.easemob.com";
    private $orgName = "1192161211115671";
    private $appName = "coolman";
    private $clientId = "YXA6f0iAAL-cEeaq_l9iUL4eTg";
    private $clientSecret = "YXA6eRnRx6121xKdQdNYrSv8aqYdYdo";
}